import React, { useMemo } from 'react'
import { Tooltip } from 'antd'

interface StoryboardRow {
  id: string
  order: number
  image?: string
  shotType: string
  duration: number
  content: string
  notes: string
}

interface TimelineSegment {
  id: string
  order: number
  startTime: number
  endTime: number
  duration: number
  title: string
  shotType: string
  percentage: number
  content: string
  notes: string
  hasImage: boolean
}

interface StoryboardTimelineProps {
  rows: StoryboardRow[]
  onSegmentClick?: (rowId: string, order: number) => void
  currentSelectedId?: string
}

const StoryboardTimeline: React.FC<StoryboardTimelineProps> = ({
  rows,
  onSegmentClick,
  currentSelectedId
}) => {
  const timelineData = useMemo(() => {
    const totalDuration = rows.reduce((sum, row) => sum + row.duration, 0)
    let currentTime = 0
    
    const segments: TimelineSegment[] = rows.map((row) => {
      const startTime = currentTime
      const endTime = currentTime + row.duration
      const percentage = totalDuration > 0 ? (row.duration / totalDuration) * 100 : 0
      
      currentTime = endTime
      
      return {
        id: row.id,
        order: row.order,
        startTime,
        endTime,
        duration: row.duration,
        title: row.content || `场景 ${row.order}`,
        shotType: row.shotType,
        percentage,
        content: row.content || '',
        notes: row.notes || '',
        hasImage: !!(row.image && row.image.trim())
      }
    })
    
    return { segments, totalDuration }
  }, [rows])

  const getShotTypeLabel = (shotType: string): string => {
    const labelMap: { [key: string]: string } = {
      'extreme_wide': '超远景',
      'wide': '远景',
      'medium_wide': '中远景',
      'medium': '中景',
      'medium_close': '中近景',
      'close_up': '近景',
      'extreme_close': '特写',
      'detail': '细节'
    }
    return labelMap[shotType] || shotType
  }

  const getShotTypeColor = (shotType: string): string => {
    const colorMap: { [key: string]: string } = {
      'extreme_wide': '#13c2c2',
      'wide': '#52c41a',
      'medium_wide': '#1890ff',
      'medium': '#722ed1',
      'medium_close': '#fa8c16',
      'close_up': '#fa541c',
      'extreme_close': '#eb2f96',
      'detail': '#f5222d'
    }
    return colorMap[shotType] || '#8c8c8c'
  }

  const formatTime = (seconds: number): string => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}:${secs.toString().padStart(2, '0')}`
  }

  const handleSegmentClick = (segment: TimelineSegment) => {
    onSegmentClick?.(segment.id, segment.order)
  }

  if (timelineData.segments.length === 0) {
    return (
      <div style={{ 
        padding: '20px', 
        textAlign: 'center', 
        color: '#999',
        border: '1px dashed #d9d9d9',
        borderRadius: '6px',
        backgroundColor: '#fafafa'
      }}>
        暂无场景数据
      </div>
    )
  }

  return (
    <div style={{
      backgroundColor: 'white',
      padding: '20px',
      borderRadius: '8px',
      border: '1px solid #e8e8e8',
      boxShadow: '0 2px 8px rgba(0,0,0,0.06)'
    }}>
      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: '12px'
      }}>
        <h4 style={{ margin: 0, fontSize: '16px', fontWeight: 600 }}>
          时间轴视图
        </h4>
        <span style={{ 
          color: '#666', 
          fontSize: '14px',
          fontWeight: 500
        }}>
          总时长: {formatTime(timelineData.totalDuration)}
        </span>
      </div>
      
      <div style={{
        display: 'flex',
        height: '60px',
        border: '1px solid #e8e8e8',
        borderRadius: '6px',
        overflow: 'hidden',
        backgroundColor: '#f8f9fa',
        boxShadow: 'inset 0 1px 2px rgba(0,0,0,0.05)'
      }}>
        {timelineData.segments.map((segment) => {
          const isSelected = segment.id === currentSelectedId
          const backgroundColor = getShotTypeColor(segment.shotType)
          
          return (
            <Tooltip
              key={segment.id}
              title={
                <div style={{ maxWidth: '280px' }}>
                  <div style={{ 
                    fontSize: '14px', 
                    fontWeight: 600, 
                    marginBottom: '8px',
                    borderBottom: '1px solid rgba(255,255,255,0.3)',
                    paddingBottom: '4px'
                  }}>
                    场景 {segment.order}: {segment.title}
                  </div>
                  
                  <div style={{ marginBottom: '6px' }}>
                    <strong>景别:</strong> {getShotTypeLabel(segment.shotType)}
                  </div>
                  
                  <div style={{ marginBottom: '6px' }}>
                    <strong>时长:</strong> {segment.duration}秒
                  </div>
                  
                  <div style={{ marginBottom: '6px' }}>
                    <strong>时间:</strong> {formatTime(segment.startTime)} - {formatTime(segment.endTime)}
                  </div>
                  
                  {segment.content && (
                    <div style={{ marginBottom: '6px' }}>
                      <strong>内容:</strong> {segment.content.length > 50 ? segment.content.substring(0, 50) + '...' : segment.content}
                    </div>
                  )}
                  
                  {segment.notes && (
                    <div style={{ marginBottom: '6px' }}>
                      <strong>备注:</strong> {segment.notes.length > 30 ? segment.notes.substring(0, 30) + '...' : segment.notes}
                    </div>
                  )}
                  
                  {segment.hasImage && (
                    <div style={{ 
                      color: '#52c41a',
                      fontSize: '12px',
                      marginTop: '4px'
                    }}>
                      📷 包含画面
                    </div>
                  )}
                </div>
              }
              placement="top"
              overlayStyle={{ maxWidth: '320px' }}
            >
              <div
                style={{
                  width: `${segment.percentage}%`,
                  height: '100%',
                  backgroundColor,
                  cursor: 'pointer',
                  position: 'relative',
                  border: isSelected ? '3px solid #1890ff' : '1px solid rgba(255,255,255,0.2)',
                  boxSizing: 'border-box',
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'center',
                  alignItems: 'center',
                  transition: 'all 0.2s ease',
                  opacity: isSelected ? 1 : 0.85
                }}
                onClick={() => handleSegmentClick(segment)}
                onMouseEnter={(e) => {
                  e.currentTarget.style.opacity = '1'
                  e.currentTarget.style.transform = 'scale(1.02)'
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.opacity = isSelected ? '1' : '0.85'
                  e.currentTarget.style.transform = 'scale(1)'
                }}
              >
                <div style={{
                  color: 'white',
                  fontSize: '12px',
                  fontWeight: 600,
                  textShadow: '0 1px 2px rgba(0,0,0,0.5)',
                  textAlign: 'center',
                  lineHeight: '1.2',
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: '1px'
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '2px' }}>
                    {segment.order}
                    {segment.hasImage && (
                      <span style={{ fontSize: '10px' }}>📷</span>
                    )}
                  </div>
                  {segment.percentage > 8 && (
                    <div style={{
                      fontSize: '10px'
                    }}>
                      {segment.duration}s
                    </div>
                  )}
                  {segment.percentage > 12 && segment.content && (
                    <div style={{
                      fontSize: '8px',
                      maxWidth: '100%',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap'
                    }}>
                      {segment.content.length > 6 ? segment.content.substring(0, 6) + '...' : segment.content}
                    </div>
                  )}
                </div>
              </div>
            </Tooltip>
          )
        })}
      </div>
      
      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        marginTop: '8px',
        fontSize: '12px',
        color: '#666'
      }}>
        <span>0:00</span>
        <span>{formatTime(timelineData.totalDuration)}</span>
      </div>
      
      <div style={{
        display: 'flex',
        flexWrap: 'wrap',
        gap: '8px',
        marginTop: '16px'
      }}>
        {['extreme_wide', 'wide', 'medium_wide', 'medium', 'medium_close', 'close_up', 'extreme_close', 'detail'].map(shotType => {
          const hasScenes = timelineData.segments.some(s => s.shotType === shotType)
          if (!hasScenes) return null

          return (
            <div key={shotType} style={{
              display: 'flex',
              alignItems: 'center',
              gap: '4px',
              fontSize: '12px',
              color: '#666'
            }}>
              <div style={{
                width: '12px',
                height: '12px',
                backgroundColor: getShotTypeColor(shotType),
                borderRadius: '2px'
              }} />
              <span>{getShotTypeLabel(shotType)}</span>
            </div>
          )
        })}
      </div>
    </div>
  )
}

export default StoryboardTimeline